package com.kgd.news.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.ehcache.CacheKit;
import com.kgd.news.bean.VideoInfoModel;
import com.kgd.news.entity.*;
import com.kgd.news.utils.*;
import com.kgd.news.utils.db.DbSychronizationController;
import com.kgd.news.utils.wx.VideoHelper;
import com.kgd.news.utils.wx.WxHelper;
import org.apache.commons.codec.digest.DigestUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.lang.reflect.Method;
import java.security.*;
import java.security.spec.InvalidParameterSpecException;
import java.sql.SQLException;
import java.util.*;
import java.util.regex.Pattern;

import static com.kgd.news.utils.Api.D_204;
import static com.kgd.news.utils.Api.E_201;
import static com.kgd.news.utils.Api.L_404;

/**
 * @Email: huangsanm@foxmail.com
 * @Date: 2017/9/24
 * @Time: 下午4:10
 */
public class IndexController extends ApiController {

    /**
     * 获取微信openid
     */
    public void getOpenUserId() {
        String code = getPara("wx_code");
        String result = WxHelper.requestWxOpenId(code);
        if (!StringUtils.isEmpty(result)) {
            JSONObject data = JSONObject.parseObject(result);
            renderJson(new Api(data).get());
        } else {
            renderJson(new Api(E_201, null).get());
        }
    }

    public void test() {
        Image image = new Image();
        image.setRealurl("https://v.qq.com/x/page/f0505lwxwa7.html");

        VideoHelper.transUrlTovalid(image);
    }

    /**
     * 获取微信openid,微信规定
     */
    public void decodeUserInfo() {

        String encryptedData = getPara("encryptedData");
        encryptedData = encryptedData.replace(" ", "+");
        String session_key = getPara("session_key");
        session_key = session_key.replace(" ", "+");
//        String aesKey = StringUtils.decodeByBase64(session_key);
        String iv = getPara("iv");
        iv = iv.replace(" ", "+");

//        getUserInfo(encryptedData1,session_key1,iv1);
        try {
//            String encryptedData = "+lVEkrSy7TeIUyXEcoaOEHZH4Lggvx63p+3RxGftRsY4JizAHCj4SBrvtMM25ZWLPg7GiJ0jEZFc4CVsC8OjZnWMKHrobwn79Yyk4Cwarz7uJfRU6VKAeYyWgYMjOf9tNaC9nyS12INp/SIaYrv3cA==";
//            String session_key = "Ky26I8q35bb+SBb6xZCNmg==";
//        String aesKey = StringUtils.decodeByBase64(session_key);
//            String iv = "kh/VxJhrQOezHmGooS4gag==";
            byte[] dataByte = decodeBase64(encryptedData);
            byte[] keyByte = decodeBase64(session_key);
            byte[] ivByte = decodeBase64(iv);
//      iv = "kh/VxJhrQOezHmGooS4gag==";
//            Base64 base64 = new Base64();
//            base64.decode(encryptedData);
            // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                JSONObject data = JSONObject.parseObject(result);
                renderJson(new Api(data).get());
            } else {
                renderJson(new Api(E_201, null).get());
            }
            return;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidParameterSpecException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        renderJson(new Api(E_201, null).get());
    }

    /***
     * decode by Base64
     */
    public static byte[] decodeBase64(String input) throws Exception {
        Class clazz = Class.forName("com.sun.org.apache.xerces.internal.impl.dv.util.Base64");
        Method mainMethod = clazz.getMethod("decode", String.class);
        mainMethod.setAccessible(true);
        Object retObj = mainMethod.invoke(null, input);
        return (byte[]) retObj;
    }

    /**
     * 用户登录
     */
    public void login() {
        String from = getPara("froms");
        if (StringUtils.isEmpty(from)) {
            renderJson(new Api(D_204, "参数错误").get());
            return;
        }
        String userid = getPara("userid");//openid
        if (StringUtils.isEmpty(userid)) {
            renderJson(new Api(D_204, "参数错误").get());
            return;
        }
        SysUser user = SysUser.dao.findFirst("select * from sys_user where userid = ?", userid);
        if (user != null) {
            if (user.getStatus() == 2) {
                renderJson(new Api(Api.L_206, null, "用户已被冻结"));
            } else {
                renderJson(new Api(user).get());
            }
            return;
        }
        String logo = getPara("logo");// 头像
        int sex = getParaToInt("sex");//1男，0女
        String name = getPara("name");//微信昵称
        String address = getPara("address");//地址
        user = new SysUser();
        user.setSname(name);
        user.setCreatetime(DateUtils.getCurDate());
        user.setSex(sex);
        user.setAddress(address);
        user.setLogo(logo);
        user.setUserid(userid);
        user.setFroms(from);
        if (user.save()) {
            renderJson(new Api(user, "登录成功").get());
        } else {
            renderJson(new Api(E_201, "登录失败").get());
        }
    }

    /**
     * 获取系统设置
     */
    public void getSettings() {
        List<SysSettings> object = CacheKit.get("cache", "setting");
        if (object != null) {
        } else {
            object = SysSettings.dao.find("select * from sys_settings");
            CacheKit.put("cache", "setting", object);
        }
        renderJson(new Api(object).get());
    }

    /**
     * 获取类别
     */
    public void getCategoryList() {
        String parentid = getPara("categoryid");
        List<Category> list = CacheKit.get("category", "category" + parentid);
        if (list != null && list.size() > 0) {
        } else {
            list = Category.dao.find("select * from category where parentid = ? order by corder desc", parentid);
            CacheKit.put("category", "category" + parentid, list);
        }
        renderJson(new Api(list).get());
    }

    /**
     * 获取资讯列表
     */
    public void getNewsList() {
        String sql = "from news where 1=1 ";
        String cateogryid = getPara("categoryid");
        String title = getPara("title");
        JSONObject json = CacheKit.get("news", "news" + title + cateogryid + getPageIndex());
        if (json != null) {
        } else {
            if (!StringUtils.isEmpty(cateogryid) && !"-1".equals(cateogryid)) {
                sql += " and categoryid = " + cateogryid;
            }
            if (!StringUtils.isEmpty(title)) {
                sql += " and title like '%" + title + "%'";
            }
            String sql1 = sql;
            sql += " and isbanner = 2 ";
            if ("-1".equals(cateogryid)) {
                sql += " order by readtimes desc";
            } else {
                sql += "order by id desc";
            }
            Page<News> data = News.dao.paginate(getPageIndex(), PAGE_SIZE, "select *", sql);
            //List<News> list = News.dao.find(sql);
            json = new JSONObject();
            json.put("newsList", data.getList());
            json.put("pageIndex", data.getPageNumber());
            json.put("pageCount", data.getTotalPage());
            json.put("isLastPage", data.isLastPage());
            //获取推荐列表
            sql1 = "select * " + sql1 + " and isbanner = 1 order by id desc limit 0, 2";
            List<News> list1 = News.dao.find(sql1);
            json.put("bannerList", list1);
            CacheKit.put("news", "news" + title + cateogryid + getPageIndex(), json);
        }
        renderJson(new Api(Api.S_200, json).get());
    }

    /**
     * 资讯详情
     */
    public void getNewsDetail() {
        String newsId = getPara("newsid");
        Integer genderInt = getParaToInt("gender");
        News news = News.dao.findById(newsId);
        String xtype = getPara("xtype");
        if (StringUtils.isEmpty(xtype)) {
            news.setReadtimes(news.getReadtimes() + 1);
            news.update();
        }
        String url = news.getVideourl();
        if (url == null || url.isEmpty()) {
            if (!StringUtils.isEmpty(news.getVideorealurl())) {
                VideoHelper.transUrlTovalid(news);
            }
        } else {
            if (url.endsWith("mp4")) {
            } else {
                String updateurltime = news.getUpdateurltime();
                if (updateurltime == null || updateurltime.isEmpty()) {
                    VideoHelper.transUrlTovalid(news);
                } else {
//                    配置文件配置
                    // TODO: 2017/11/21
                    boolean isVideoOutOfTime = DateUtils.isOutOfTime(updateurltime, 4 * 60);
                    if (isVideoOutOfTime) {
                        VideoHelper.transUrlTovalid(news);
                    }
                }
            }
        }
        JSONObject object = CacheKit.get("news", "newsdetail" + newsId + genderInt + getPageIndex());
        if (object != null) {
        } else {
            object = new JSONObject();
            object.put("news", news);
            Page<Comment> data = Comment.dao.paginate(getPageIndex(), PAGE_SIZE, "select *", "from comment where otherid = ?", newsId);
            object.put("comments", data.getList());
            object.put("pageIndex", data.getPageNumber());
            object.put("isLastPage", data.isLastPage());
            String sql = "select * from news where categoryid = ? and id <> " + newsId + " order by id desc limit 0, 2";
            List<News> newsList = News.dao.find(sql, news.getCategoryid());
            object.put("newsList", newsList);
            if (genderInt == null) {
                object.put("adv", Adv.dao.findFirst("select * from adv where categoryid = ? ", news.getCategoryid()));
            } else {
                object.put("adv", Adv.dao.findFirst("select * from adv where categoryid = ? and gender = ?", news.getCategoryid(), genderInt));
            }
            CacheKit.put("news", "newsdetail" + newsId + genderInt + getPageIndex(), object);
        }
        renderJson(new Api(object).get());
    }


    /**
     * 资讯详情
     */
    public void getNewsDetailForce() {
        String newsId = getPara("newsid");
        Integer genderInt = getParaToInt("gender");
        News news = News.dao.findById(newsId);
        String xtype = getPara("xtype");
        if (StringUtils.isEmpty(xtype)) {
            news.setReadtimes(news.getReadtimes() + 1);
            news.update();
        }
        String url = news.getVideourl();
        if (url == null || url.isEmpty()) {
        } else {
            if (url.endsWith("mp4")) {
            } else {
                VideoHelper.transUrlTovalid(news);
            }
        }
        JSONObject object = CacheKit.get("news", "newsdetail" + newsId + genderInt + getPageIndex());
        if (object != null) {
        } else {
            object = new JSONObject();
            object.put("news", news);
            Page<Comment> data = Comment.dao.paginate(getPageIndex(), PAGE_SIZE, "select *", "from comment where otherid = ?", newsId);
            object.put("comments", data.getList());
            object.put("pageIndex", data.getPageNumber());
            object.put("isLastPage", data.isLastPage());
            String sql = "select * from news where categoryid = ? and id <> " + newsId + " order by id desc limit 0, 2";
            List<News> newsList = News.dao.find(sql, news.getCategoryid());
            object.put("newsList", newsList);
            if (genderInt == null) {
                object.put("adv", Adv.dao.findFirst("select * from adv where categoryid = ? ", news.getCategoryid()));
            } else {
                object.put("adv", Adv.dao.findFirst("select * from adv where categoryid = ? and gender = ?", news.getCategoryid(), genderInt));
            }
            CacheKit.put("news", "newsdetail" + newsId + genderInt + getPageIndex(), object);
        }
        renderJson(new Api(object).get());
    }

    /**
     * 发布评论
     */
    public void writeComment() {
        Long userid = getParaToLong("userid");
        String content = getPara("content");
        Long otherid = getParaToLong("otherid");
        String mtype = getPara("mtype");
        if (StringUtils.isEmpty(content)) {
            return;
        }
        SysUser su = SysUser.dao.findById(userid);
        Comment c = new Comment();
        c.setUserid(userid);
        c.setContent(content);
        c.setOtherid(otherid);
        c.setLogo(su.getLogo());
        c.setName(su.getSname());
        c.setCreattime(DateUtils.getCurDate(DateUtils.COMMON_DATETIME));
        final boolean flag = c.save();
        renderJson(new Api(flag).get());
        updateComments(mtype, otherid);
    }

    /**
     * 更新评论次数
     *
     * @param type
     * @param otherid
     */
    private void updateComments(String type, Long otherid) {
        if ("news".equals(type)) {
            Db.update("update news set commenttimes = commenttimes + 1 where id = ?", otherid);
//            外面的也要更改
            CacheKit.removeAll("news");
        } else if ("image".equals(type)) {
//            只有详细的页面可以通过id来精细控制一点吧。
            CacheKit.removeAll("imageAndVideo");
            CacheKit.removeAll("video");
            CacheKit.removeAll("image");
            Db.update("update image set commenttimes = commenttimes + 1 where id = ?", otherid);
        }


    }


    /**
     * 点赞
     */
    public void doFavForContent() {
        Long cid = getParaToLong("cid");
        //1:news,2:image，3:comment
        Integer xtype = getParaToInt("xtype");
        int flag = 0;
        if (xtype == 1) {
            flag = Db.update("update news set favtimes = favtimes + 1 where id = ?", cid);
            CacheKit.removeAll("news");
        } else if (xtype == 2) {
            flag = Db.update("update image set favtimes = favtimes + 1 where id = ?", cid);
            CacheKit.removeAll("video");
            CacheKit.removeAll("image");
            CacheKit.removeAll("imageAndVideo");
        } else if (xtype == 3) {
//            评论列表是没有缓存的，用的地方少
            flag = Db.update("update comment set fav = fav + 1 where id = ?", cid);
//            CacheKit.removeAll("imageAndVideo");
//            CacheKit.removeAll("news");
//            CacheKit.removeAll("vidoe");
//            CacheKit.removeAll("image");
        }
        renderJson(new Api(flag > 0).get());
    }

    /**
     * 解析腾讯视频数据
     */
    public void parseTencent() {
        String rearUrl = getPara("rearUrl");
        String validUrl = VideoHelper.transUriToValid(rearUrl);
        JSONObject data = new JSONObject();
        data.put("validUrl", validUrl);
        renderJson(new Api(data).get());
    }

    /**
     * 获取图片列表
     */
    public void getImageList() {
        String sql = "from image where type = 1 ";
        String cateogryid = getPara("categoryid");
        String title = getPara("title");
        JSONObject object = CacheKit.get("image", "image" + title + cateogryid + getPageIndex());
        if (object != null) {
        } else {
            if (!StringUtils.isEmpty(cateogryid) && !"-1".equals(cateogryid)) {
                sql += " and categoryid = " + cateogryid;
            }
            if (!StringUtils.isEmpty(title)) {
                sql += " and title like '%" + title + "%'";
            }
            if ("-1".equals(cateogryid)) {
                sql += " order by readtimes desc";
            } else {
                sql += " order by id desc";
            }
            Page<Image> data = Image.dao.paginate(getPageIndex(), PAGE_SIZE, "select * ", sql);
            object = new JSONObject();
            object.put("imageList", data.getList());
            object.put("pageIndex", data.getPageNumber());
            object.put("isLastPage", data.isLastPage());
            CacheKit.put("image", "image" + title + cateogryid + getPageIndex(), object);
        }

        renderJson(new Api(object).get());
    }

    /**
     * 获取图片和视频详情
     */
    public void getImgAndVideoDetail() {
        String imgid = getPara("imgid");
        Image image = Image.dao.findById(imgid);
        if (image == null) {
            renderError(Api.D_204, "未发现改imgid=" + imgid + "的资源");
        }

        Integer genderInt = getParaToInt("gender");

        String xtype = getPara("xtype");
        if (StringUtils.isEmpty(xtype)) {
            image.setReadtimes(image.getReadtimes() + 1);
            image.update();
        }
//        设置interrupttime为0
        Integer interrupttime = image.getInterrupttime();
        if (interrupttime == null) {
            image.setInterrupttime(0);
        }
        String url = image.getUrl();
        if (url == null || url.isEmpty()) {
            if (!StringUtils.isEmpty(image.getRealurl())) {
                VideoHelper.transUrlTovalid(image);
            }
        } else {
            if (url.endsWith("mp4")) {
            } else {
                String updateurltime = image.getUpdateurltime();
                if (updateurltime == null || updateurltime.isEmpty()) {
                    VideoHelper.transUrlTovalid(image);
                } else {
//                    配置文件配置
                    // TODO: 2017/11/21
                    boolean isVideoOutOfTime = DateUtils.isOutOfTime(updateurltime, 4 * 60);
                    if (isVideoOutOfTime) {
                        VideoHelper.transUrlTovalid(image);
                    }
                }
            }
        }
        JSONObject object = CacheKit.get("imageAndVideo", "imageAndVideo" + imgid + genderInt + getPageIndex());
        if (object != null) {

        } else {
            object = new JSONObject();
            object.put("image", image);
            List<Media> mlist = getMedia(image.getId());
            object.put("pics", mlist);
            Page<Comment> data = Comment.dao.paginate(getPageIndex(), PAGE_SIZE, "select * ", "from comment where otherid = ?", imgid);
            object.put("comments", data.getList());
            object.put("pageIndex", data.getPageNumber());
            object.put("isLastPage", data.isLastPage());
            String sql = "select * from image where categoryid = ? and id <> " + imgid + " order by id desc limit 0, 2";
            List<Image> imgList = Image.dao.find(sql, image.getCategoryid());
            JSONArray array = new JSONArray();
            for (Image img : imgList) {
                JSONObject imgjson = new JSONObject();
                imgjson.put("otherImage", img);
                List<Media> lt = getMedia(img.getId());
                if (lt != null && !lt.isEmpty()) {
                    imgjson.put("otherPic", lt.get(0));
                } else {
                    imgjson.put("potherPic", new Media());
                }
                array.add(imgjson);
            }
            object.put("img", array);
            if (genderInt == null) {
                object.put("adv", Adv.dao.findFirst("select * from adv where categoryid = ? ", image.getCategoryid()));
            } else {
                object.put("adv", Adv.dao.findFirst("select * from adv where categoryid = ? and gender = ?", image.getCategoryid(), genderInt));
            }
            CacheKit.put("imageAndVideo", "imageAndVideo" + imgid + genderInt + getPageIndex(), object);

        }
        renderJson(new Api(object).get());
    }

    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }

    /**
     * 获取图片和视频详情videoDetail  videoid
     */
    public void getImgAndVideoDetailForce() {

        String imgid = getPara("imgid");
        Image image = Image.dao.findById(imgid);
        String xtype = getPara("xtype");
        if (StringUtils.isEmpty(xtype)) {
            image.setReadtimes(image.getReadtimes() + 1);
            image.update();
        }
        String url = image.getUrl();
        if (url == null || url.isEmpty()) {
        } else {
            if (url.endsWith("mp4")) {
            } else {
                VideoHelper.transUrlTovalid(image);
            }
        }


        JSONObject object = CacheKit.get("imageAndVideo", "imageAndVideo" + imgid + getPageIndex());
        if (object != null) {

        } else {
            object = new JSONObject();
            object.put("image", image);
            List<Media> mlist = getMedia(image.getId());
            object.put("pics", mlist);
            Page<Comment> data = Comment.dao.paginate(getPageIndex(), PAGE_SIZE, "select * ", "from comment where otherid = ?", imgid);
            object.put("comments", data.getList());
            object.put("pageIndex", data.getPageNumber());
            object.put("isLastPage", data.isLastPage());
            String sql = "select * from image where categoryid = ? and id <> " + imgid + " order by id desc limit 0, 2";
            List<Image> imgList = Image.dao.find(sql, image.getCategoryid());
            JSONArray array = new JSONArray();
            for (Image img : imgList) {
                JSONObject imgjson = new JSONObject();
                imgjson.put("otherImage", img);
                List<Media> lt = getMedia(img.getId());
                if (lt != null && !lt.isEmpty()) {
                    imgjson.put("otherPic", lt.get(0));
                } else {
                    imgjson.put("potherPic", new Media());
                }
                array.add(imgjson);
            }
            object.put("img", array);
            object.put("adv", Adv.dao.findFirst("select * from adv where categoryid = ?", image.getCategoryid()));
            CacheKit.put("imageAndVideo", "imageAndVideo" + imgid + getPageIndex(), object);
        }
        renderJson(new Api(object).get());
    }

    /**
     * 获取视频列表
     */
    public void getVideoList() {
        String sql = "from image where type = 2 ";
        String cateogryid = getPara("categoryid");
        String title = getPara("title");
        JSONObject object = CacheKit.get("video", "video" + title + cateogryid + getPageIndex());
        if (object != null) {
        } else {
            if (!StringUtils.isEmpty(cateogryid) && !"-1".equals(cateogryid)) {
                sql += " and categoryid = " + cateogryid;
            }
            if (!StringUtils.isEmpty(title)) {
                sql += " and title like '%" + title + "%'";
            }
            if ("-1".equals(cateogryid)) {
                sql += " order by readtimes desc";
            } else {
                sql += " order by id desc";
            }
            Page<Image> data = Image.dao.paginate(getPageIndex(), PAGE_SIZE, "select * ", sql);
            object = new JSONObject();
            object.put("imageList", data.getList());
            object.put("pageIndex", data.getPageNumber());
            object.put("isLastPage", data.isLastPage());
            CacheKit.put("video", "video" + title + cateogryid + getPageIndex(), object);
        }
        renderJson(new Api(object).get());
    }


    /**
     * 获取测试列表
     */
    public void getQuestionList() {
        String sql = "from question where 1 = 1 ";
        String cateogryid = getPara("categoryid");
        String title = getPara("title");
        JSONObject object = CacheKit.get("question", "question" + title + cateogryid + getPageIndex());
        if (object != null) {
        } else {
            if (!StringUtils.isEmpty(cateogryid) && !"-1".equals(cateogryid)) {
                sql += " and type = " + cateogryid;
            }
            if (!StringUtils.isEmpty(title)) {
                sql += " and title like '%" + title + "%'";
            }
            String sql1 = sql;
            if ("-1".equals(cateogryid)) {
                sql += " and isbanner = 2 order by testing desc";
            } else {
                sql += " and isbanner = 2 order by id desc";
            }
            Page<Question> data = Question.dao.paginate(getPageIndex(), PAGE_SIZE, "select * ", sql);
            object = new JSONObject();
            object.put("questionList", data.getList());
            object.put("pageIndex", data.getPageNumber());
            object.put("isLastPage", data.isLastPage());
            //获取推荐列表
            sql1 = "select * " + sql1 + " and isbanner = 1 order by id desc limit 0, 2";
            List<Question> list1 = Question.dao.find(sql1);
            object.put("bannerList", list1);
            CacheKit.put("question", "question" + title + cateogryid + getPageIndex(), object);
        }
        renderJson(new Api(Api.S_200, object).get());
    }


    /**
     * 获取测试详情
     */
    public void getQuestionDetail() {
        String questionid = getPara("questionid");
//        int genderInt = getParaToInt("gender");

        Question q = Question.dao.findById(questionid);
        q.setTesting(q.getTesting() + 1);
        q.update();
        JSONObject json = new JSONObject();
        json.put("question", q);
        List<Question> qlist = Question.dao.find("select * from question q where q.type = ? order by q.id desc limit 0, 5", q.getType());
        json.put("others", qlist);
//        json.put("adv", Adv.dao.findFirst("select * from adv where categoryid = ? and gender = ?", q.getType(),genderInt));

        renderJson(new Api(json).get());
    }

    /**
     * 获取列表
     */
    public void getOptions() {
        String questionid = getPara("questionid");
        Question q = Question.dao.findById(questionid);
        List<Options> list = Options.dao.find("select * from options where questionid = ? order by sort desc", questionid);
        JSONObject json = new JSONObject();
        json.put("question", q);
        json.put("optionList", list);
        renderJson(new Api(json).get());
    }

    /**
     * 获取小程序列表
     */
    public void getSmallAppList() {
//        54宝贝55发现
        String cateogryid = getPara("categoryid");
        JSONObject json = CacheKit.get("smallapp", "smallapp" + cateogryid);
        if (json != null) {
        } else {
            json = new JSONObject();
            List<Smallapp> list = Smallapp.dao.find("select * from smallapp where categoryid = ? order by id desc", cateogryid);
            json.put("smallAppList", list);
            CacheKit.put("smallapp", "smallapp" + cateogryid, json);
        }
        renderJson(new Api(json).get());
    }

    /**
     * 验证密码是否正确
     */
    public void checkPasswd() {
        String passwd = getPara("passwd");
        int id = getParaToInt("id");
        int type = getParaToInt("xtype");//1：新闻，2：图片视频
        int uesrid = getParaToInt("userid");
        boolean flag = false;
        if (type == 1) {
            News n = News.dao.findById(id);
            if (n != null) {
                saveContent(passwd, id, type, uesrid);
                flag = passwd.equals(n.getPasswd());
            }
        } else if (type == 2) {
            Image img = Image.dao.findById(id);
            if (img != null) {
                saveContent(passwd, id, type, uesrid);
                flag = passwd.equals(img.getPasswd());
            }
        }
        renderJson(new Api(flag).get());
    }

    private void saveContent(String passwd, int id, int type, int uesrid) {
        if (!StringUtils.isEmpty(passwd)) {
            UserContentPwd ucp = new UserContentPwd();
            ucp.setUserid(uesrid);
            ucp.setOtherid(id);
            ucp.setPasswd(passwd);
            ucp.setType(type);
            ucp.save();
        }
    }

    /**
     * 获取评论列表
     */
    public void getCommentList() {
        Long otherid = getParaToLong("otherid");
        List<Comment> list = Comment.dao.find("select * from comment where otherid = ?", otherid);
        renderJson(new Api(list).get());
    }

    public void getPasswdRoute() {
        String sql = "select * from adv where type = 2";
        Adv adv = Adv.dao.findFirst(sql);
        renderJson(new Api(adv).get());
    }

    /**
     * 提交测试结果
     */
    public void submitResult() {
        Integer score = getParaToInt("score");
        Long questionid = getParaToLong("questionid");
        Long userid = getParaToLong("userid");
        Question q = Question.dao.findById(questionid);
        Results rlt = new Results();
        rlt.setScore(score);
        rlt.setQuestionid(questionid);
        rlt.setUserid(userid);
        rlt.save();
        JSONObject json = new JSONObject();
        json.put("others", rlt.getId());
//        json.put("adv", Adv.dao.findFirst("select * from adv where categoryid = ?", q.getType()));
        renderJson(new Api(json).get());

    }

    /**
     * 生成测试结果
     */
    public void createResults() {
        Long questionid = getParaToLong("questionid");
        Integer score = getParaToInt("score");
        Long userid = getParaToLong("userid");
        Long resultid = getParaToLong("resultid");
        Integer genderInt = getParaToInt("gender");

        Question q = Question.dao.findById(questionid);
        JSONObject json = new JSONObject();
        json.put("question", q);
        List<Question> qlist = Question.dao.find("select * from question q where q.type = ? order by q.id desc limit 0, 5", q.getType());
        json.put("others", qlist);
        //s_score <= score <= e_score
        Score s = Score.dao.findFirst("select * from score where questionid = ? and s_score <= ? and e_score >= ?", questionid, score, score);
        json.put("score", s);
        if (genderInt == null) {
            json.put("adv", Adv.dao.findFirst("select * from adv where categoryid = ? ", q.getType()));
        } else {
            json.put("adv", Adv.dao.findFirst("select * from adv where categoryid = ? and gender = ?", q.getType(), genderInt));
        }
        renderJson(new Api(json).get());
    }

    /**
     * 记录访问vip的记录，下次访问不再需要输入密码
     */
    public void cacheContentPwd() {
        int userid = getParaToInt("userid");
        int otherid = getParaToInt("otherid");
        String pwd = getPara("pwd");
        //1、资讯；2、图片；3、测试
        int type = getParaToInt("xtype");
        String passwd = "";
        if (type == 1) {
            News n = News.dao.findById(otherid);
            if (n != null) {
                passwd = n.getPasswd();
            }
        } else if (type == 2) {
            Image img = Image.dao.findById(otherid);
            if (img != null) {
                passwd = img.getPasswd();
            }
        }
        String sql = "select * from user_content_pwd where userid = ? and otherid = ? and type = ? and passwd = ?";
        UserContentPwd ucp1 = UserContentPwd.dao.findFirst(sql, userid, otherid, type, passwd);
        if (ucp1 == null) {
            renderJson(new Api(true).get());
        } else {
            renderJson(new Api(false).get());
        }
    }


    private List<Media> getMedia(long otherid) {
        //Map<Long, List<Media>> map = new HashMap<>();
        return Media.dao.find("select * from media where otherid = ?", otherid);
        /*List<Media> list = new ArrayList<>();
        for (Media m : data) {
            if (!map.containsKey(m.getOtherid())){
                map.put(m.getOtherid(), list);
                list = new ArrayList<>();
            }
            list.add(m);
        }
        return map;*/
    }

    /**
     *
     */
    public void checkSignature() {
        log.error("checkSignature");

//        {
//            "ToUserName": "toUser",
//                "FromUserName": "fromUser",
//                "CreateTime": 1482048670,
//                "MsgType": "event",
//                "Event": "user_enter_tempsession",
//                "SessionFrom": "sessionFrom"
//        }
        String signature = getPara("signature");
        String timestamp = getPara("timestamp");
        String nonce = getPara("nonce");
        String echostr = getPara("echostr");
        if (!StringUtils.isEmpty(signature) && !StringUtils.isEmpty(timestamp) && !StringUtils.isEmpty(nonce) && !StringUtils.isEmpty(echostr)) {
            String token = Constants.XCX_TOKEN;
            ArrayList<String> list = new ArrayList<String>();
            list.add(nonce);
            list.add(timestamp);
            list.add(token);
            Collections.sort(list);
            String tempStr = DigestUtils.shaHex(list.get(0) + list.get(1) + list.get(2));
//微信返回的加密串
            if (tempStr.equals(signature)) {
                renderText(echostr);
            } else {
                renderText("false");
            }
        } else {
            log.error("checkSignature-else");
            //        微信推送信息
            try {
                BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream) getRequest().getInputStream()));
                String line = null;
                StringBuilder sb = new StringBuilder();
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                //sb为微信返回的xml
                String notityJson = sb.toString();
                log.error("notityJson"+notityJson);

                if (!StringUtils.isEmpty(notityJson)) {
                    String toUser = JSON.parseObject(notityJson).getString("ToUserName");
                    String FromUserName = JSON.parseObject(notityJson).getString("FromUserName");
                    String MsgType = JSON.parseObject(notityJson).getString("MsgType");
                    String Event = JSON.parseObject(notityJson).getString("Event");
//                进入会话事件
//                {
//                    "ToUserName": "toUser",
//                        "FromUserName": "fromUser",
//                        "CreateTime": 1482048670,
//                        "MsgType": "event",
//                        "Event": "user_enter_tempsession",
//                        "SessionFrom": "sessionFrom"
//                }
                    boolean isEvent = "event".endsWith(MsgType);
                    if (isEvent) {
//                    判断如果是事件的化，就要回复，
//                    服务器收到请求必须做出下述回复，这样微信服务器才不会对此作任何处理，并且不会发起重试，否则，将出现严重的错误提示。详见下面说明：
//                    1、直接回复success（推荐方式）
//                    2、直接回复空串（指字节长度为0的空字符串，而不是结构体中content字段的内容为空）
                        String messageJson = WxHelper.createJsonHelper(FromUserName);
                        log.error("messageJson"+messageJson);
                        String accessToken = WxHelper.requestAccessToke();
                        WxHelper.requestUrlPost(Constants.SENDMESSAGE+accessToken, messageJson);
                        renderText("success");
                    } else {
//               否则直接转发就好
//                    开发者只在响应包中返回 MsgType 为 transfer_customer_service 的消息，微信服务器收到响应后就会把当次发送的消息转发至客服系统。
// <xml>
//     <ToUserName><![CDATA[touser]]></ToUserName>
//     <FromUserName><![CDATA[fromuser]]></FromUserName>
//     <CreateTime>1399197672</CreateTime>
//     <MsgType><![CDATA[transfer_customer_service]]></MsgType>
// </xml>
                        String transfer_customer_xml = WxHelper.generateTransferXml(FromUserName,toUser);
                        log.error("transfer_customer_xml"+transfer_customer_xml);
                        renderText(transfer_customer_xml);
                    }
//                $postObj =json_decode($postStr);
//                $fromUsername = $postObj->FromUserName;  //openid
//                $toUsername = $postObj->ToUserName;
//                $keyword = trim($postObj->Content);
//                $MsgType = $postObj->MsgType;//消息类型 text event
//                $time = time();
//                logger($postStr);
//                //读取设置json
//                $json = file_get_contents('kefu/json/'.$toUsername.'.json');
//                $arr = json_decode($json,true);
//                define("APPID", $arr['APPID']);
//                define("APPSECRET", $arr['APPSECRET']);
//                //获取access_token
//                $token_access_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".APPID."&secret=".APPSECRET;
//                logger( $token_access_url);
//                $res = file_get_contents($token_access_url); //获取文件内容或获取网络请求的内容
//                $result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP 变量
//                $Atoken = $result['access_token'];  //
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void saveOpenid() {
        String openid = getPara("openid");
        String formid = getPara("formid");
        Xcxmessage xcxmessage = new Xcxmessage();
        xcxmessage.setFormid(formid);
        xcxmessage.setOpenid(openid);
        xcxmessage.setCreatetime(System.currentTimeMillis());
        xcxmessage.setIsvalid(1);
        xcxmessage.save();
    }

    public void sendTemplate(VideoInfoModel videoInfoModel) {
        long cutTime = System.currentTimeMillis() - 7 * 24 * 60 * 1000 * 60L;
        List<Xcxmessage> xcxmessageList = Xcxmessage.dao.find("select * from xcxmessage where createtime > " + cutTime + " group by openid");
        String accessTokeJson = WxHelper.requestAccessToke();
        if (!StringUtils.isEmpty(accessTokeJson)) {
            String access_token = JSON.parseObject(accessTokeJson).getString("access_token");
            String url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" + access_token;
            for (Xcxmessage xcxmessage :
                    xcxmessageList) {
                WxHelper.sentTemplateMessage(url, xcxmessage, videoInfoModel, "");
//                xcxmessage.dao().deleteById(xcxmessage.getId());
                Db.update("delete from xcxmessage where id = " + xcxmessage.getId());
            }
        }
    }

    public void getSystemDict() {
        String name = getPara("name");
        List<SysDict> list = SysDict.dao.find("select * from sys_dict where name = ?", name);
        if (list != null && list.size() == 1) {
            SysDict sysDict = list.get(0);
            renderText(sysDict.getDValue());
        } else {
            renderText("not find");
        }
    }

    public void getAccessToken() {
        String accessToken = WxHelper.requestAccessToke();
//        HttpServletRequest request = getRequest();
        if (StringUtils.isEmpty(accessToken)) {
            renderJson(new Api(D_204, accessToken).get());
        } else {
            renderJson(new Api(accessToken).get());
        }
    }

    public void getQrCodeByB() {
        HttpServletRequest request = getRequest();
        String filePath = WxHelper.getQrCodeB(request);
//        getFileUploadPath()
        if (!StringUtils.isEmpty(filePath)) {
//            getResponse().setContentType("image/png");
            if (filePath.contains("failure")) {
                renderJson(new Api(E_201,filePath,filePath).get());
            } else {
                renderJson(new Api(filePath).get());
            }
        } else {
            renderJson(new Api(D_204, filePath).get());
        }
    }

    public void clearCache() {
        CacheKit.removeAll("news");
        CacheKit.removeAll("image");
        CacheKit.removeAll("imageAndVideo");
        CacheKit.removeAll("smallapp");
        CacheKit.removeAll("cache");
        CacheKit.removeAll("category");
        CacheKit.removeAll("video");
        renderText("success");
    }

    public void clearCacheAll() {
        List<Dbtable> dbtables = Dbtable.dao.find("select * from dbtable ");
//            password=bsmysqladmin
//            jdbcUrl1=jdbc:mysql://116.255.202.75/
        for (Dbtable dbtable : dbtables
                ) {
            String tempJdbcUrl = dbtable.getJdbcurl();
            String tempProjectname = dbtable.getTablename();
//                jdbc:mysql://127.0.0.1:3306/
            String url_clear = tempJdbcUrl.replace("jdbc:mysql://", "") + tempProjectname + "/api/clearCache";
            WxHelper.requestUrl(url_clear);
        }
        renderText("success");
    }

//    https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=ACCESS_TOKEN
}
